import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { EntityDtoOfGuid, FrontendPageServiceProxy, IEntityDtoOfGuid, NameValue, SetStatusInput, } from '@shared/service-proxies/service-proxies';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { finalize } from 'rxjs/operators';
import { CreateOrEditPageModalComponent } from './create-or-edit-page-modal.component';
import { PageViewModalComponent } from './pageview-modal.component';


@Component({
    templateUrl: './frontendPage.component.html',
    animations: [appModuleAnimation()]
})
export class FrontendPageComponent extends AppComponentBase {

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;
    @ViewChild('createOrEditPageModal', { static: true }) createOrEditPageModal: CreateOrEditPageModalComponent;
    @ViewChild('pageViewModal', { static: true }) pageViewModal: PageViewModalComponent;

    filterText = '';
    selectedDatas: IEntityDtoOfGuid[];
    loading = false;

    backendPageList: NameValue[] = [];
    backendPageList2: NameValue[] = [];

    actionNames = [
        { name: '栏目页面', isShow: true },
        { name: '详情页', isShow: true },
        { name: '独立页面', isShow: true }];

    currentIndex: number = 0;
    onTabSelect(e, i) {
        this.selectedDatas = [];
        this.currentIndex = i;
        this.getListData();
    }

    backEndModuleId: string = '';


    constructor(
        injector: Injector,
        private _frontendPageService: FrontendPageServiceProxy,
        private _activatedRoute: ActivatedRoute,
        private _router: Router) {
        super(injector);
    }

    ngAfterViewInit(): void {
        setTimeout(() => {
            this.init();
        });
    }

    init() {
        this._activatedRoute.params.subscribe((params: Params) => {
            this.backEndModuleId = params['backEndModuleId'] || '';

            this.getListData(null);
        });

        this.loading = true;
        this._frontendPageService.getAllModuleData()
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                this.backendPageList = result;

                // 给另一个页面用，后者的空值选项不能为null
                let backendData2 = [
                    new NameValue({ name: this.l("UnSelect"), value: '00000000-0000-0000-0000-000000000000' })
                ];
                backendData2 = backendData2.concat(this.backendPageList.slice(1));
                this.backendPageList2 = backendData2;
            });
    }

    getListData(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }

        this.selectedDatas = [];

        this.primengTableHelper.showLoadingIndicator();
        this._frontendPageService.getPagedFrontendPages(
            this.backEndModuleId,
            this.currentIndex,
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

    reloadPage() {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getListData(null);
    }

    edit(entry) {
        this.openCreateOrEdit(entry);
    };
    createNews() {
        this.openCreateOrEdit(null);
    }

    delete() {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);
        if (ids.length == 0) return;
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._frontendPageService.deleteList(ids)
                    .subscribe(() => {
                        this.selectedDatas = [];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }

    deleteSingle(entity) {
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._frontendPageService.delete(entity.id)
                    .subscribe(() => {
                        this.selectedDatas = [];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }


    changeState(state: boolean) {
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item => item.id);

        if (ids.length > 0) {
            let msg: string;
            if (state) {
                msg = this.l('ReleaseWarningMessage');
            }
            else {
                msg = this.l('UndoReleaseWarningMessage');
            }
            this.message.confirm(msg, this.l('AreYouSure'),
                (isConfirmed) => {
                    if (!isConfirmed) return;

                    let input = new SetStatusInput();
                    input.idList = ids;
                    input.isActive = state;

                    this._frontendPageService.setStatus(input)
                        .subscribe(() => {
                            this.selectedDatas = [];
                            this.getListData(null);
                            if (state) {
                                this.notify.success(this.l('ReleaseSuccessfully'));
                            } else {
                                this.notify.success(this.l('CancelReleaseSuccessfully'));
                            }
                        });
                })
        }
    }

    openCreateOrEdit(entry) {
        if (entry) {
            this.createOrEditPageModal.show(this.backEndModuleId, entry.id, this.backendPageList2);
        } else {
            this.createOrEditPageModal.show(this.backEndModuleId, undefined, this.backendPageList2);
        }
    }

    copy(entity) {
        this.loading = true;
        this._frontendPageService.copyNewOne(new EntityDtoOfGuid({ id: entity.id }))
            .pipe(finalize(() => this.loading = false))
            .subscribe(result => {
                this.notify.success(this.l('CopySuccessfully'));
                this.getListData(null);
            });
    }

    goPageView(entity) {
        this.pageViewModal.show(entity.id, entity.name);
    }
}
